package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.data.group.ANblock;
import org.akomantoso.core.io.Externalizable;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.Output;
import org.akomantoso.core.visitor.AKVisitor;

/**
 * <pre>
 * <xsd:element name="toc">
 * 		<xsd:complexType>
 * 			<xsd:sequence>
 * 				<xsd:element ref="tocItem" minOccurs="1" maxOccurs="unbounded"/>
 * 			</xsd:sequence>
 * 	</xsd:complexType>
 * </xsd:element>
 * </pre>
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 * @since http://www.akomantoso.org/1.0
 */
public final class Toc implements ANblock, Externalizable {

	public static final String ELEMENT = "toc";

	private final List<TocItem> _tocItems = new ArrayList<TocItem>(4);

	public List<TocItem> getTocItems() {
		return _tocItems;
	}

	public void addTocItem(TocItem item) {
		_tocItems.add(item);
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		for (int i = 0, n = _tocItems.size(); i < n; i++) {
			_tocItems.get(i).writeExternal(out);
		}
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	public <T extends Input> void readExternal(T in) throws IOException {
		TocItem item;
		int eventType = in.readNext();
		while (true) {
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				if (TocItem.ELEMENT.equals(in.getLocalName())) {
					_tocItems.add(item = new TocItem());
					item.readExternal(in);
				}
				break;
			case InputConstants.END_ELEMENT:
				if (ELEMENT.equals(in.getLocalName())) {
					return;
				}
			}
			eventType = in.readNext();
		}
	}

	/**
	 * @see ec.ep.visitor.AKVisitable#accept(ec.ep.visitor.AKVisitor)
	 */
	public void accept(AKVisitor visitor) {
		throw new RuntimeException();
	}
}